<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="配置名称" prop="configName">
        <el-input
          v-model="queryParams.configName"
          placeholder="请输入配置名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="操作类型" prop="operationType">
        <el-select
          v-model="queryParams.operationType"
          placeholder="请选择操作类型"
          clearable
          class="!w-240px"
        >
          <el-option label="人脸注册" value="register" />
          <el-option label="人脸搜索" value="search" />
          <el-option label="人脸检测" value="detect" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option label="成功" :value="1" />
          <el-option label="失败" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
        <el-button
          type="danger"
          plain
          @click="handleDelete"
          :disabled="!multiple"
          v-hasPermi="['infra:face-record:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" />
          删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="记录ID" align="center" prop="id" width="80" />
      <el-table-column label="配置名称" align="center" prop="configName" width="120" show-overflow-tooltip />
      <el-table-column label="文件名" align="center" prop="fileName" width="150" show-overflow-tooltip />
      <el-table-column label="图片" align="center" prop="imageUrl" width="100">
        <template #default="scope">
          <div class="image-cell">
            <el-image
              :src="scope.row.imageUrl"
              class="table-image"
              fit="cover"
              :preview-src-list="[scope.row.imageUrl]"
              preview-teleported
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作类型" align="center" prop="operationType" width="100">
        <template #default="scope">
          <el-tag :type="getOperationTagType(scope.row.operationType)" size="small">
            {{ getOperationText(scope.row.operationType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="用户ID" align="center" prop="userId" width="120" show-overflow-tooltip />
      <el-table-column label="用户组ID" align="center" prop="groupId" width="120" show-overflow-tooltip />
      <el-table-column label="相似度" align="center" prop="score" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.score" :type="getScoreTagType(scope.row.score)" size="small">
            {{ Math.round(scope.row.score * 100) }}%
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="人脸数量" align="center" prop="faceCount" width="100" />
      <el-table-column label="处理时间" align="center" prop="processTime" width="100">
        <template #default="scope">
          <span v-if="scope.row.processTime">{{ scope.row.processTime }}ms</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
            {{ scope.row.status === 1 ? '成功' : '失败' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
        :formatter="dateFormatter"
      />
      <el-table-column label="操作" align="center" width="150">
        <template #default="scope">
          <div style="display: flex; gap: 8px; justify-content: center;">
            <el-button
              type="primary"
              size="small"
              plain
              @click="openDetail(scope.row)"
            >
              <Icon icon="ep:view" class="mr-5px" />
              详情
            </el-button>
            <el-button
              type="danger"
              size="small"
              plain
              @click="handleDelete([scope.row.id])"
              v-hasPermi="['infra:face-record:delete']"
            >
              <Icon icon="ep:delete" class="mr-5px" />
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 记录详情弹窗 -->
  <el-dialog
    v-model="detailVisible"
    title="记录详情"
    width="800px"
    :close-on-click-modal="false"
    class="detail-dialog"
  >
    <div v-if="detailData" class="detail-content">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="记录ID">{{ detailData.id }}</el-descriptions-item>
            <el-descriptions-item label="配置名称">{{ detailData.configName || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="文件名">{{ detailData.fileName }}</el-descriptions-item>
            <el-descriptions-item label="操作类型">
              <el-tag :type="getOperationTagType(detailData.operationType)">
                {{ getOperationText(detailData.operationType) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="用户ID">{{ detailData.userId || '-' }}</el-descriptions-item>
            <el-descriptions-item label="用户组ID">{{ detailData.groupId || '-' }}</el-descriptions-item>
            <el-descriptions-item label="识别状态">
              <el-tag :type="detailData.status === 1 ? 'success' : 'danger'">
                {{ detailData.status === 1 ? '成功' : '失败' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item v-if="detailData.score" label="相似度">
              <el-tag :type="getScoreTagType(detailData.score)">
                {{ Math.round(detailData.score * 100) }}%
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item v-if="detailData.faceCount" label="人脸数量">
              {{ detailData.faceCount }}
            </el-descriptions-item>
            <el-descriptions-item v-if="detailData.processTime" label="处理时间">
              {{ detailData.processTime }}ms
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDateTime(detailData.createTime) }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :span="12">
          <div class="detail-image-container">
            <el-image
              :src="detailData.imageUrl"
              class="detail-image"
              fit="contain"
              :preview-src-list="[detailData.imageUrl]"
              preview-teleported
            />
          </div>
        </el-col>
      </el-row>
      
      <div v-if="detailData.errorMessage" class="error-section">
        <el-divider>错误信息</el-divider>
        <el-alert
          :title="detailData.errorMessage"
          type="error"
          :closable="false"
          show-icon
        />
      </div>
      
      <div v-if="detailData.remark" class="remark-section">
        <el-divider>备注信息</el-divider>
        <el-input
          v-model="detailData.remark"
          type="textarea"
          :rows="3"
          readonly
          class="detail-textarea"
        />
      </div>
    </div>
    
    <template #footer>
      <el-button @click="detailVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { dateFormatter, formatDateTime } from '@/utils/formatTime'
import { getFaceRecordPage, deleteFaceRecord } from '@/api/infra/face'

/** 人脸记录查询 */
defineOptions({ name: 'InfraFaceRecord' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  configName: '',
  userId: '',
  operationType: '',
  status: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const selectedIds = ref([]) // 表格的选中 ID 数组

// 详情弹窗
const detailVisible = ref(false)
const detailData = ref(null)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getFaceRecordPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map(item => item.id)
}

/** 是否有选中 */
const multiple = computed(() => selectedIds.value.length > 0)

/** 删除按钮操作 */
const handleDelete = async (ids?: number[]) => {
  const deleteIds = ids || selectedIds.value
  if (deleteIds.length === 0) {
    message.warning('请选择要删除的记录')
    return
  }
  
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteFaceRecord(deleteIds)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
    selectedIds.value = []
  } catch {}
}

/** 打开详情 */
const openDetail = (row: any) => {
  detailData.value = row
  detailVisible.value = true
}

/** 获取操作类型标签 */
const getOperationTagType = (type: string) => {
  switch (type) {
    case 'register': return 'primary'
    case 'search': return 'success'
    case 'detect': return 'warning'
    default: return 'info'
  }
}

/** 获取操作类型文本 */
const getOperationText = (type: string) => {
  switch (type) {
    case 'register': return '注册'
    case 'search': return '搜索'
    case 'detect': return '检测'
    default: return '未知'
  }
}

/** 获取相似度标签类型 */
const getScoreTagType = (score: number) => {
  if (score >= 0.8) return 'success'
  if (score >= 0.6) return 'warning'
  return 'danger'
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped>
.image-cell {
  display: flex;
  justify-content: center;
  align-items: center;
}

.table-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}

.detail-dialog .detail-content {
  padding: 0;
}

.detail-image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.detail-image {
  max-width: 100%;
  max-height: 100%;
}

.error-section,
.remark-section {
  margin-top: 20px;
}

.detail-textarea {
  margin-top: 8px;
}
</style>